<!DOCTYPE html>
<html lang="en">

<head>
  <meta charset="UTF-8">
  <meta http-equiv="X-UA-Compatible" content="IE=edge">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>typed Array</title>
</head>

<body>
  <script>
    //ArrayBuffer()
    const buf = new ArrayBuffer(16);//在内存中分配16字节
    console.log(buf.byteLength);//16
    const buf2 = buf.slice(2, 12);
    console.log(buf2.byteLength);//10

    //DateView
    const fullDateView = new DataView(buf);
    console.log(fullDateView.byteOffset, fullDateView.byteLength, fullDateView.buffer === buf);

    const firstHalfDateView = new DataView(buf, 0, 8)//截取前[0-8]前8个缓冲.
    console.log(firstHalfDateView.byteOffset, firstHalfDateView.byteLength, firstHalfDateView.buffer === buf);

    const secondHalfDateView = new DataView(buf, 8)//从8开始截取缓冲.
    console.log(secondHalfDateView.byteOffset, secondHalfDateView.byteLength, secondHalfDateView.buffer === buf);

    const buf3 = new ArrayBuffer(2);//分配了两个字节,1字节 = 8比特
    const view = new DataView(buf3);
    console.log(view.getInt8(0));//0
    console.log(view.getInt8(1));//0
    // console.log(view.getInt8(2));//报错
    // console.log(view.getInt16(1))//报错
    view.setUint8(0, 255);
    view.setUint8(1, 0xff);
    console.log(view.getInt8(1));

    const buffer = new ArrayBuffer(12); //12字节的缓冲
    const ints = new Int32Array(buffer);//每个元素需要4个字节;
    console.log(ints.length);//3

    const ints2 = new Int32Array(6);//长度为6,6*4=24字节缓冲
    console.log(ints2.buffer.byteLength);//24

    const ints3 = new Int32Array([2, 4, 6, 8]);
    console.log(ints3.length);//4
    console.log(ints3.buffer.byteLength);//4*4=16

    const ints4 = new Int16Array([1, 2, 3]);
    for (const int of ints4) {
      console.log(int)//1,2,3
    }
    console.log(Math.max(...ints4));//3

    // set()
    const container = new Int16Array(8);//长度为8的定型数组
    container.set(Int8Array.of(1, 2, 3, 4));
    console.log(container);//[1,2,3,4,0,0,0,0]
    // 从索引4开始插入.
    container.set([5, 6, 7, 8], 4);
    console.log(container);//
    //subarray()
    const source = Int16Array.of(2, 4, 6, 8);
    const fullCopy = source.subarray();
    console.log(fullCopy);//
    const halfCopy = source.subarray(2);//从索引2开始复制.
    console.log(halfCopy);//[6,8]
  </script>
</body>

</html>